;
(function () {
  Array.prototype.removeRepeatBuildingAndFLoor = function () {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  var withdrawId = hlUrlUtil.GetQueryString('id');

  var hireEdit = new Vue({
    el: '#hireEdit',
    data: {
      contractId: '',
      projectId: '',
      withdraw: {},
      contract: {
        ot: [],
        st: []
      },
      receiveData: [],
      refundData: [],
      matchData: [], // 模糊匹配的费项
      contractExpense: [], // 与合同相关的费项
      newReceiveData: [],
      newRefundData: [],
      newTodoList: [],
      newFile: [],
      withdrawReason: [],
      withdrawReasonActive: '',
      pics: [],
      todoList: [],
      sum: {
        receiveTotal: 0,
        refundTotal: 0
      },
      isReceiveMatch: false,
      uploadBtn: true,
      title: '',
      totalTip: '应收',
      wfMoney: 0,
      yfMoney: 0,
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数
      wpTotalNum: 0, // 工位总数
      totalArea: 0, // 单元总面积
      building: [], // 楼宇信息
      projectName: null, // 项目名
      unitOpenFlag: true,
      wpOpenFlag: true,
      stOpenFlag: true,
      //20190705
      flag: false,
      ktflag: true,
      flowtype: '',
      expenditureList: [],
      regExpenditureList: [],
      tzDate: '',

      progress: '',
      fileList: [],

      contractId: hlUrlUtil.GetQueryString('id'),
      conflictBills: [],
    },
    filters: {
      formatDate: function (time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      formatNum: function (item) {
        if (item == '--') return '--'
        return hlNumberUtil.formatNum(item)
      },
      auditState: function (state) {
        return hlCodeConvert.withdrawAuditState(state)
      }
    },
    computed: {
      total() {
        let result = 0;
        this.expenditureList.map((item, index) => {
          result += Number(item.expense_amount)
        })
        this.regExpenditureList.map(item => {
          result -= Number(item.expense_amount)
        })
        return result
      }
    },
    methods: {
      // 根据退租日期生成退租结算信息
      getWithdrawDate() {
        let data = {
          withdraw_date: this.tzDate,
          contract_id: this.contractId
        }
        hlhttp.get({
          url: 'withdraw/balance_info/by_withdraw_date',
          data: data,
          success: res => {
            res.conflictBills.map(item => {
              item.expenses.map(single => {
                if (single.withdrawAmount) {
                  single.withdrawAmount.amountRefund = (Number(single.withdrawAmount.amountPayed) + Number(single.withdrawAmount.derateExpense) + Number(single.withdrawAmount.carryOverAmount) - Number(single.withdrawAmount.amountReceive)).toFixed(2)
                }
                if (single.amount) {
                  single.amount.amountRefund = (Number(single.amount.amountPayed) + Number(single.amount.derateExpense) + Number(single.amount.carryOverAmount) - Number(single.amount.amountReceive)).toFixed(2)
                }
              })
            })
            this.conflictBills = res.conflictBills || []

            this.refundData = this.refundData.filter(item => {
              return item.mac_flag == 'Y'
            })
            this.receiveData = this.receiveData.filter(item => {
              return item.mac_flag == 'Y'
            })


            if (res.withdrawRefundExpenses && res.withdrawRefundExpenses.length) {
              res.withdrawRefundExpenses.map(item => {
                if (item.amount > 0) {
                  this.refundData.push({
                    amount: item.amount,
                    expenditureId: item.expenditureId,
                    expense_name: item.expenseName,
                    flowtype: item.flowType,
                    memo: item.memo,
                    type: item.type,
                    rate: item.taxFee,
                    percentage: item.lateFee,
                    mac_flag: 'N',
                    isShow: true,
                  })
                }
                if (item.amount < 0) {
                  this.receiveData.push({
                    amount: item.amount,
                    expenditureId: item.expenditureId,
                    expense_name: item.expenseName,
                    flowtype: item.flowType,
                    memo: item.memo,
                    type: item.type,
                    mac_flag: 'N',
                    isShow: true,
                  })
                }
              })
            }
          }
        })
      },


      // 相关文件
      uploadFile: function () {
        if (this.progress) {
          hl.toast('文件尚未上传完成')
          return
        }
        $('.upload-file-button').trigger('click')
      },
      // 删除上传的文件
      delFileItem(index) {
        this.fileList.splice(index, 1)
      },
      // 保存文件
      saveFile() {
        if (!this.fileList.length) return
        let nameList = []
        let urlList = []
        this.fileList.map(item => {
          nameList.push(item.name)
          urlList.push(item.url)
        })

        let data = {
          withdraw_id: withdrawId,
          attachment_name: nameList + '',
          attachment_url: urlList + '',
        }
        hlhttp.put({
          url: 'withdraw_attachment',
          data: data,
          success: function (res) {

          },
        })
      },

      queryExpenditure(ops) {
        console.log(ops)
        this.flag = false
        if (!ops.name) return
        ops.expense_name = ops.name
        ops.mac_flag = 'Y'
        ops.isShow = true
        ops.flowtype = this.flowtype
        if (this.flowtype == 'RC') {
          this.receiveData.push(ops)
        } else {
          this.refundData.push(ops)
        }
      },
      // 获取合同单元信息
      getContractUnitsData: function () {
        var self = this;
        hlhttp.get({
          url: 'contract/units',
          data: {
            id: self.contractId
          },
          success: function (data) {
            // 单元
            var buildingData = self.dealWithUnitData(data)
            self.totalArea = buildingData.totalArea
            self.building = buildingData.building
            // 车位
            self.st = [];
            self.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            data.map(function (item) {
              if (item.positions && item.unitType === 'ST') {
                stTotalNum = stTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.st.push(item)
              }
              if (item.positions && item.unitType === 'WP') {
                wpTotalNum = wpTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.wp.push(item)
              }
            })
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      // 单元数据去重整合处理
      dealWithUnitData: function (unitsData) {
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function (_item) {
          if (_item.positions.length === 0) {
            units.push(_item)
          }
        })
        if (units.length === 0) {
          return {
            building: [],
            totalArea: 0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i < units.length; i++) {
          unit.push({
            buildingName: units[i].buildingName,
            floorNum: units[i].floorNum,
            unit: []
          })
        }
        var unitArr = unit.removeRepeatBuildingAndFLoor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j < unitArr.length; j++) {
          building.push({
            buildingName: unitArr[j].buildingName,
            floor: []
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum': unitArr[n].floorNum,
                'unit': unitArr[n].unit
              })
            }
          }
        }
        return {
          building: buildingArr,
          totalArea: totalArea
        }
      },
      // 查看出租资源详情信息
      checkDetailMes: function (type) {
        var self = this;
        if (type === 'unit') {
          if (self.unitOpenFlag === true) {
            self.unitOpenFlag = false
            return false
          }
          if (self.unitOpenFlag === false) {
            self.unitOpenFlag = true
            return false
          }
        }
        if (type === 'wp') {
          if (self.wpOpenFlag === true) {
            self.wpOpenFlag = false;
            return false;
          }
          if (self.wpOpenFlag === false) {
            self.wpOpenFlag = true
            return false;
          }
        }
        if (type === 'st') {
          if (self.stOpenFlag === true) {
            self.stOpenFlag = false
            return false;
          }
          if (self.stOpenFlag === false) {
            self.stOpenFlag = true
            return false;
          }
        }
      },
      //获取退租时间
      pageName: function (name) {
        window.localStorage.setItem('cname', name)
      },
      getTZdate: function () {
        var _this = this;

        function dateA() {
          setTimeout(function () {
            _this.timeDate = true;
            if (!_this.tzDate) return;
            hlhttp.get({
              url: 'contract/wp_bill_count,ape_bill_count',
              data: {
                contract_id: _this.contractId,
                withdraw_time: _this.tzDate
              },
              success: function (res) {
                aflag = true;
                _this.wfMoney = res.wp_bill_count
                _this.yfMoney = res.ape_bill_count
              }
            })
          }, 300);
        }
        dateA()
        $('.dt-dateControl').on('click', function () {
          var aflag = false;
          if (aflag) return;
          dateA()
        })
      },
      // 验证应收费项
      validateReceiveExpense: function (val, i) {
        if (!hlNumberUtil.isNum(val)) {
          this.$set(this.$data.receiveData[i], 'amount', '0')
          return
        }
        if (!val.length) {
          hl.toast('费用不能为空')
          return
        }
      },
      validateReceiveExpense2: function (val, i) {
        if (val.length === 0) {
          this.$set(this.$data.receiveData[i], 'amount', '0')
        }
      },
      // 验证应退费项
      validateRefundExpense: function (val, i) {
        if (!hlNumberUtil.isNum(val)) {
          this.$set(this.$data.refundData[i], 'amount', '0')
        }
        if (!val.length) {
          hl.toast('费用不能为空')
          return
        }
      },
      validateRefundExpense2: function (val, i) {
        if (val.length === 0) {
          this.$set(this.$data.refundData[i], 'amount', '0')
        }
      },
      // 匹配应收费项
      matchReceiveExpense: function (val, i) {
        var self = this
        self.contractExpense.map(function (item) {
          if (item.expenseName.indexOf(val) >= 0 && val) {
            self.matchData = []
            self.matchData.push(item)
            self.isReceiveMatch = true
          }
        })
      },
      // 匹配应退费项
      matchRefundExpense: function (val, i) {
        var self = this
        self.contractExpense.map(function (item) {
          if (item.expenseName.indexOf(val) >= 0 && val) {
            self.matchData = []
            self.matchData.push(item)
            self.isReceiveMatch = true
          }
        })
      },
      // 隐藏费项
      hideExpense: function () {
        this.isReceiveMatch = false;
      },
      // 获取退租详情数据
      getData: function () {
        var self = this;
        hlhttp.get({
          url: 'withdraw,expenses',
          data: {
            id: withdrawId
          },
          success: function (data) {
            if (data.files && data.files.length) {
              data.files.map((item, index) => {
                self.fileList.push({
                  name: data.fileNames[index],
                  url: item
                })
              })
            }
            loginPrem.loginList()
            self.withdraw = data
            self.judgeEditStatus()
            // 数据处理
            var receiveData = [];
            var refundData = [];
            data.expenses.map(function (item) {
              var obj = {
                expense_name: item.name,
                amount: item.amount,
                type: item.type,
                memo: item.memo,
                flowtype: item.flowType,
                expenditureId: item.expenditureId,
                rate: item.taxPercent * 100,
                percentage: item.lateFeePercent * 100,
                mac_flag: item.macFlag,
                isShow: true
              }
              if (item.name == '租金' || item.name == '押金/保证金') {
                obj['isShow'] = false
              }
              if (item.paymentType === 'R') {
                receiveData.push(obj)
              }
              if (item.paymentType === 'W') {
                refundData.push(obj)
              }
            })
            self.receiveData = receiveData;
            self.refundData = refundData;

            // var files = [];
            // if(data.files){
            //   for (var i = 0; i < data.files.length; i++) {
            //     files.push({
            //       name: data.fileNames[i],
            //       src: data.files[i]
            //     })
            //   }
            // }
            // self.files = files;
            data.conflictBills.map(item => {
              item.expenses.map(single => {
                if (single.withdrawAmount) {
                  single.withdrawAmount.amountRefund = (Number(single.withdrawAmount.amountPayed) + Number(single.withdrawAmount.derateExpense) + Number(single.withdrawAmount.carryOverAmount) - Number(single.withdrawAmount.amountReceive)).toFixed(2)
                }
                if (single.amount) {
                  single.amount.amountRefund = (Number(single.amount.amountPayed) + Number(single.amount.derateExpense) + Number(single.amount.carryOverAmount) - Number(single.amount.amountReceive)).toFixed(2)
                }
              })
            })

            self.conflictBills = data.conflictBills
            self.contractId = data.contractId;
            self.projectId = data.projectId;
            self.todoList = data.todoList ? data.todoList : [];
            self.pics = data.pics || [];
            self.withdrawReasonActive = data.reason
            self.tzDate = hlDateUtil.formatUTCDate(data.withdrawDate, 'yyyy-MM-dd')
            loginPrem.loginList()
            self.getExpenseData()
            self.getTZdate()
            self.getContractUnitsData()
            window.contract.formatUnitData(data.contractId, function (_data) {
              self.contract = _data
            })

          }
        })
      },
      // 获取退租原因数据
      getWithdrawReasonsData: function () {
        var self = this;
        hlhttp.get({
          url: 'withdraw_reasons',
          success: function (data) {
            self.withdrawReason = data
          }
        })
      },
      // 获取合同关联费项数据
      getExpenseData: function () {
        var self = this;
        hlhttp.get({
          url: 'contract/expenses',
          data: {
            contract_id: self.contractId
          },
          success: function (data) {
            self.contractExpense = data
          }
        })
      },
      // 判断当前编辑状态
      judgeEditStatus: function () {
        var self = this
        if (self.withdraw.auditState === 'CG') {
          self.title = '退租管理—草稿'
        }
        if (self.withdraw.auditState === 'FBP') {
          self.title = '退租管理—业务审核不通过'
        }
        if (self.withdraw.auditState === 'FCP') {
          self.title = '退租管理—财务审核不通过'
        }
      },
      // 弹出添加应收费项框
      showAddReceiveExpense: function (val) {
        if (this.newReceiveData.length === 1) return false
        this.flag = true
        this.flowtype = val
      },
      // 取消添加应收费项框
      cancelAddReceiveExpense: function (i) {
        this.newReceiveData.splice(i, 1)
        this.matchData = []
      },
      // 删除应收费项
      delReceiveExpense: function (i) {
        this.receiveData.splice(i, 1);
      },
      // 添加应收费项
      addReceiveExpense: function (i) {
        // 输入框验证
        var _name = this.newReceiveData[0].expense_name;
        var _amount = this.newReceiveData[0].amount;
        var _memo = this.newReceiveData[0].memo;

        if (_name === '') {
          hl.toast('费项名不能为空')
          $('.receive-name').focus()
          return false
        }
        if (!hlNumberUtil.isPositiveNumber(_amount)) {
          hl.toast('费用必须为正数')
          return false
        }
        for (j = 0; j < this.receiveData.length; j++) {
          if (this.receiveData[j].expense_name == _name) {
            hl.toast('费项名不能重复')
            $('.receive-name').focus()
            return false;
          }
        }
        this.$set(this.$data, 'receiveData', this.receiveData.concat(this.newReceiveData))
        this.newReceiveData.splice(i, 1)
        this.matchData = []
      },
      // 弹出添加应退费项框
      showAddRefundExpense: function (val) {
        if (this.newRefundData.length === 1) {
          return false
        }
        this.flag = true
        this.flowtype = val
        // this.newRefundData.push({
        //   expense_name: '',
        //   amount: '',
        //   memo: '',
        //   type: 'T',
        //   isShow: true
        // });
      },
      // 取消添加应退费项框
      cancelAddRefundExpense: function (i) {
        this.newRefundData.splice(i, 1)
      },
      // 添加应退费项
      addRefundExpense: function (i) {
        // 输入框验证
        var _name = this.newRefundData[0].expense_name;
        var _amount = this.newRefundData[0].amount;
        var _memo = this.newRefundData[0].memo;

        if (_name === '') {
          hl.toast('费项名不能为空')
          $('.refund-name').focus()
          return false
        }
        if (!hlNumberUtil.isPositiveNumber(_amount)) {
          hl.toast('费用必须为正数')
          return false
        }
        for (j = 0; j < this.refundData.length; j++) {
          if (this.refundData[j].expense_name == _name) {
            hl.toast('费项名不能重复')
            $('.refund-name').focus()
            return false;
          }
        }

        this.$set(this.$data, 'refundData', this.refundData.concat(this.newRefundData))
        this.newRefundData.splice(i, 1)
        this.matchData = []
      },
      // 删除应收费项
      delRefundExpense: function (i) {
        this.refundData.splice(i, 1);
      },
      selectedReceiveExpense: function (name, type) {
        this.newReceiveData[0].expense_name = name
        this.newReceiveData[0].type = type
        this.isReceiveMatch = false
      },
      selectedRefundExpense: function (name, type) {
        this.newRefundData[0].expense_name = name
        this.newRefundData[0].type = type
        this.isReceiveMatch = false
      },

      //删除待办事项
      delTodoItem: function (i) {
        this.todoList.splice(i, 1)
      },
      //弹出待办事项输入框
      showTodoIpt: function () {
        if (this.newTodoList.length === 1) {
          return false
        }
        this.newTodoList.push('');
      },
      // 取消
      cancelTodoIpt: function (i) {
        this.newTodoList.splice(i, 1)
      },
      // 添加
      addTodoItem: function (i) {
        if (!this.newTodoList[i]) {
          hl.toast('待办事项不能为空')
          return
        }
        this.$set(this.$data, 'todoList', this.todoList.concat(this.newTodoList[i]))
        this.newTodoList.splice(i, 1)
      },
      showBigImage: function (i) {
        console.log(this.pics);
        $.imageShow(this.pics, i)
      },
      showFile(i){
        let fileL = this.fileList.map(item=>item.url)
        if(['gif','jpg','jpeg','png','bmp','GIF','JPG','PNG'].includes(fileL[i].split('.')[fileL[i].split('.').length-1])){
          $.imageShow(fileL, i)
        }else{
          hl.toast('该文件不支持预览')
        }
      },
      delImage: function (i) {
        this.pics.splice(i, 1)
      },
      uploadImage: function () {
        var self = this
        imgupload('.upload-image', uploadUrl, function (src) {
          self.pics.push(JSON.parse(src.response).url)
        })
      },
      // uploadFile: function () {
      //   var self = this;
      //   fileUpload('.upload-file', uploadUrl, function (src) {
      //     self.files.push({
      //       name: src.name,
      //       src: JSON.parse(src.response).url
      //     })
      //   })
      // },
      // delFile: function (i) {
      //   this.files.splice(i, 1);
      // },
      // 编辑保存
      confirmEdit: function (sucFn) {
        var self = this
        var receiveData = [];
        var refundData = [];
        // var files = [];
        var fileNames = [];

        var beginDate = self.contract.beginDate;
        var endDate = self.contract.endDate;
        var hireDate = '';

        if (self.withdraw.auditState === 'FCP') {
          // hireDate = self.withdraw.withdrawDate;
					hireDate = new Date(self.withdraw.withdrawDate + ' 00:00:00').getTime();
        }
        if (self.withdraw.auditState === 'CG' || self.withdraw.auditState === 'FBP') {
          hireDate = new Date(self.tzDate + ' 00:00:00').getTime();
        }
        if (hireDate < beginDate || hireDate > endDate) {
          hl.toast('退租时间不在合同生效日期范围')
          return
        }

        self.receiveData.map(function (_item) {
          var obj = {
            amount: _item.amount.toString(),
            expense_name: _item.expense_name,
            memo: _item.memo || '#',
            type: _item.type,
            flow_type: _item.flowtype,
            expenditure_id: _item.expenditureId || '#',
            tax_percent: _item.rate ? _item.rate / 100 + '' : '#',
            late_fee_percent: _item.percentage / 100 + '',
            mac_flag: _item.mac_flag

          }
          receiveData.push(obj)
        })
        self.refundData.map(function (_item) {
          var obj = {
            amount: _item.amount.toString(),
            expense_name: _item.expense_name,
            memo: _item.memo || '#',
            type: _item.type,
            flow_type: _item.flowtype,
            expenditure_id: _item.expenditureId || '#',
            tax_percent: _item.rate ? _item.rate / 100 + '' : '#',
            late_fee_percent: _item.percentage / 100 + '',
            mac_flag: _item.mac_flag
          }
          refundData.push(obj)
        })

        var data = {
          id: withdrawId,
          withdraw_date: self.tzDate || hlDateUtil.formatUTCDate(self.withdraw.withdrawDate, 'yyyy-MM-dd'),
          w_code: self.withdraw.wCode,
          zlf_name: self.withdraw.zlfName,
          project_id: self.withdraw.projectId,
          contract_id: self.withdraw.contractId,
          reason: self.withdraw.reason,
          todo_list: self.todoList ? self.todoList.join(',') : '#',
          pics: self.pics.join(',') || '#',
          memo: self.withdraw.memo || '#',
          receive: JSON.stringify(receiveData),
          refund: JSON.stringify(refundData)
        }
        console.log(data)   
        hlhttp.put({
          url: 'withdraw',
          data: data,
          success: function (data) {
            self.saveFile()
            hl.toast('保存成功')
            hlUrlUtil.goTo('withdrawList', {
              ddtab: true
            })
          }
        })
      },
      // 退租原因
      selectedReason: function (val) {
        this.withdrawReasonActive = val
        this.withdraw.reason = val
      },
      // 跳转合同详情
      goToContractDeatail: function () {
        hlUrlUtil.goTo('contractNewDeatil', {
          id: this.contractId,
          ddtab: true
        }, true)
      }
    },
    computed: {
      // 应收合计
      receiveTotal: function () {
        var sum = 0;
        for (var i = 0; i < this.receiveData.length; i++) {
          sum += Number(this.receiveData[i].amount);
        }
        this.sum.receiveTotal = sum;
        return hlNumberUtil.formatNum(sum.toFixed(2));
      },
      // 应退合计
      refundTotal: function () {
        var sum = 0;
        for (var i = 0; i < this.refundData.length; i++) {
          sum += Number(this.refundData[i].amount);
        }
        this.sum.refundTotal = sum;
        return hlNumberUtil.formatNum(sum.toFixed(2));
      },
      // 总计
      total: function () {
        var all = Number(Math.abs(this.sum.receiveTotal - this.sum.refundTotal)).toFixed(2);
        this.totalTip = all >= 0 ? '(应付)' : '(应退)';
        return all
      }
    },
    mounted: function () {
      this.getData()
      this.getWithdrawReasonsData()
      // this.uploadFile()
      this.uploadImage()
      var _this = this
      fileUpload('.upload-file-button', uploadUrl, function (res) {
        _this.progress = ''
        _this.fileList.push(res.json)
      }, function (val) {
        _this.progress = parseInt((val.loaded / val.total) * 100) + '%'
      })
    }
  })

}())